import os
import json
from datetime import time
from langchain_community.chat_models import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from openai import APIConnectionError

from partofproduct import split_news

os.environ["OPENAI_API_BASE"] = 'https://oneapi.xty.app/v1'
#3.5
os.environ["OPENAI_API_KEY"] = 'sk-VEDbE0OfLniuK7eJEb7067B883944d57B1Dc2a638f8f7bBb'
#4
# os.environ["OPENAI_API_KEY"] ='sk-SS3E9A82RI9P3rUg51E24031001949D59dBa51E0CeB6D3Fb'

def split_text_into_paragraphs(text, max_chars_per_paragraph):
    """
    将文本分成多个段落，每个段落的字数不超过max_chars_per_paragraph，尽量不破坏句子的完整性。

    参数:
    - text: 要分段的文本
    - max_chars_per_paragraph: 每个段落的最大字符数

    返回:
    - 段落列表
    """
    paragraphs = []
    current_paragraph = ""
    sentences = text.split('。')  # 以句号为分隔符分割句子，适用于中文文本

    for sentence in sentences:
        sentence = sentence.strip()
        if not sentence:
            continue
        sentence += '。'  # 恢复句子末尾的句号
        if len(current_paragraph) + len(sentence) <= max_chars_per_paragraph:
            current_paragraph += sentence
        else:
            if current_paragraph:
                paragraphs.append(current_paragraph)
                current_paragraph = sentence
            else:
                # 如果单个句子长度超过最大长度，直接添加为一个段落
                paragraphs.append(sentence)

    if current_paragraph:
        paragraphs.append(current_paragraph)

    return paragraphs




def process(product,news_list):
    chat = ChatOpenAI(temperature=0.0)
    for n in news_list:
        result = ""
        news = split_news(n["content"], 400)
        for new in news:
            template_string = f"""
                            请你对文章进行预处理，保留和{product}相关的原文,去除不相关信息。
                            文章：{new}
                        """
            prompt_template = ChatPromptTemplate.from_template(template_string)
            prompts = prompt_template.format_messages(
                product=product,
                new=new
            )
            print(prompts)
            for i in range(1, 3):
                try:
                    response = chat(prompts)
                    print(response)
                except APIConnectionError as e:
                    time.sleep(10)
                    continue
                else:
                    break
            response = str(response)
            response = response.replace("content=\'", "")
            result = result + response
            result = result.replace("content=\'", "")
        n["content"]=result
    # 处理后的新闻
    print("处理后的新闻")
    print(news_list)
    # 定义一个Python字典
    return news_list

def process_v2(product,news_list):
    chat = ChatOpenAI(temperature=0.0)
    for n in news_list:
        result = ""
        news = split_news(n["content"], 400)
        for new in news:
            template_string = f"""
                            请你对文章进行预处理，保留和{product}组成结构及其供应商相关的部分,去除不相关信息。
                            文章：{new}
                        """
            prompt_template = ChatPromptTemplate.from_template(template_string)
            prompts = prompt_template.format_messages(
                product=product,
                new=new
            )
            print(prompts)
            for i in range(1, 3):
                try:
                    response = chat(prompts)
                    print(response)
                except APIConnectionError as e:
                    time.sleep(10)
                    continue
                else:
                    break
            response = str(response)
            response = response.replace("content=\'", "")
            result = result + response
            result = result.replace("content=\'", "")
        n["content"]=result
    # 处理后的新闻
    print("处理后的新闻")
    print(news_list)
    # 定义一个Python字典
    return news_list